package com.forclass.apply2;

import java.lang.reflect.*;
import java.util.Arrays;

public class ReflectMain {
    public static void main(String[] args) throws Exception {
        System.out.println("******1.获取类信息***********");
        Class<?> userClazz = Class.forName("com.forclass.apply2.User");
        System.out.println("类名：" + userClazz.getName());
        System.out.println("简单类名：" +userClazz.getSimpleName());
        System.out.println("是否为接口：" + userClazz.isInterface());

        System.out.println("******2.操作字段***********");
        Field[] fields = userClazz.getDeclaredFields();
        System.out.println("字段列表:");
        Arrays.stream(fields).forEach(f-> System.out.println(f.getName() + ":" + f.getType()));

        System.out.println("******修改私有字段值***********");
        User user = createInstance(userClazz);
        Field ageField = userClazz.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(user,20);
        System.out.println("修改后的age:" + ageField.get(user));

        System.out.println("******3.方法的操作***********");
        Method setNameMethod = userClazz.getMethod("setName", String.class);
        setNameMethod.invoke(user,"Alice");
        Method validteMethod = userClazz.getDeclaredMethod("validate");
        validteMethod.setAccessible(true);
        validteMethod.invoke(user);

        System.out.println("******4.构造函数***********");
        Constructor<?> privateCon = userClazz.getDeclaredConstructor();
        privateCon.setAccessible(true);
        User user2 = (User) privateCon.newInstance();
        System.out.println("通过私有构造方法创建的对象：" + user2);

        System.out.println("******5.泛型处理***********");
        Method genericMethod =  userClazz.getMethod("getGenericList");
        Type returnType = genericMethod.getGenericReturnType();
        if (returnType instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) returnType;
            Type[] actualTypyes = pType.getActualTypeArguments();
            System.out.println("泛型类型：" + actualTypyes);
        }

        System.out.println("******6.数组操作***********");
        Object userArray = Array.newInstance(userClazz,3);
        Array.set(userArray,0,user);
        System.out.println("数组第一个元素：" +Array.get(userArray,0));
    }

    public static User  createInstance( Class<?> clazz) throws Exception {
        Constructor<?> constructor = clazz.getConstructor(Long.class,String.class);
        return (User) constructor.newInstance(1L,"Sam");
    }
}
